const puppeteer = require('puppeteer')

const url = `https://movie.douban.com/tag/#/?sort=R&range=6,10&tags=`

// promise 定时函数
const sleep = time => new Promise(resolve => {
    setTimeout(resolve, time)
})

;
(async() => {
    console.log('start visit the target page')

    //创建一个浏览器对象
    const browser = await puppeteer.launch({
        args: ['--no-sandbox'],
        dumpio: false
    })

    const page = await browser.newPage()
    //浏览器打开这个地址,并设置加载完毕后
    await page.goto(url, {
        waitUntil: 'networkidle2'
    })

    await sleep(3000)

    //获取页面加载更多按钮
    await page.waitForSelector('.more')

    // 只获取一页
    for (let i = 0; i < 2; i++) {
        await sleep(3000)
        await page.click('.more')
    }

    console.log('a')
    const result = await page.evaluate(() => {
        var $ = window.$
        var items = $('.list-wp a')
        var links = []

        if (items.length >= 1) {
            items.each((index, el) => {
                let it = $(el)
                let doubanId = it.find('div').data('id')
                let title = it.find('.title').text()
                let rate = Number(it.find('.rate').text())
                let poster = it.find('img').attr('src').replace('s_ratio', 'l_ratio')
                // https://img3.doubanio.com/view/photo/s_ratio_poster/public/p480747492.jpg
                links.push({
                    doubanId,
                    title,
                    rate,
                    poster
                })
            });
        }

        return links
    })

    browser.close();
    console.log('------------trailer-list-------------')
    console.log(result)

    process.send({ result })
    process.exit(0)


})()